import React, {useState, useEffect, useRef} from 'react'
import { 
  Table, 
  Modal,
  Button, 
  Switch
} from 'antd';
import {
  UserOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm';

export default function UserList() {
  const [dataSource, setDataSource] = useState([])
  const [modalFlag, setModalFlag] = useState(false)
  const [roleList, setRoleList] = useState([])
  const [regoinList, setregoinList] = useState([])
  const [BtnFlag, setBtnFlag] = useState(0) // 0 新建 1 编辑
  const [updateFlag, setUpdateFlag] = useState(false)
  const addForm = useRef(null)
  const {roleId, userName} = JSON.parse(localStorage.getItem('token'))
  // 权限映射表
  const roleObj = {
    "1": "superadmin",
    "2": "admin",
    "3": "editor"
  }
  useEffect(() => {
    axios.get('/userList/getUsers').then(response => {
      const {data} = response.data
      if (data?.length > 0) {
        setDataSource(roleObj[roleId] === 'superadmin' ? data : [
          ...data.filter(item => item.userName === userName)
        ])
      }
    })
  }, [])
  useEffect(() => {
    axios.get('/userList/queryRegoinList').then(response => {
      const {data} = response.data
      if (data?.length > 0) {
        console.log('列表数据', data)
        setregoinList(data)
      }
    })
  }, [])
  useEffect(() => {
    axios.get('/userList/queryRoleList').then(response => {
      const {data} = response.data
      if (data?.length > 0) {
        setRoleList(data)
      }
    })
  }, [])

  const columns = [
    {
      title: '区域',
      align: 'center',
      dataIndex: 'region',
      filters: [
        ...regoinList.map(item => ({
          text: item.regoin,
          value: item.id
        }))
      ],
      onFilter: (value, item) => item.id === value,
      render: (region) => {
        return <b>{region}</b>
      }
    },
    {
      title: '角色名称',
      align: 'center',
      dataIndex: 'roleId'
    },
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'userName'
    },
    {
      title: '用户状态',
      align: 'center',
      render: (item) => {
        return <Switch 
          checked={item.roleState} 
          onChange={() => roleStateChange(item)}
          disabled={item.default} 
        />
      }
    },
    {
      title: '操作',
      align: 'center',
      render: (item) => {
        return <div>
        <Button 
          style={{marginRight: '5px'}}
          type="primary" 
          shape="circle" 
          icon={<UserOutlined />} 
          size='middle'
          disabled={item.default}
          onClick={() => btnClick(item)}
        />
        <Button 
          type="ghost" 
          shape="circle" 
          icon={<DeleteOutlined />} 
          size='middle'
          disabled={item.default} 
        />
        </div>
        
      }
    }
  ]

  const roleStateChange = (item) => {
    console.log(item)
    item.roleState = !item.roleState
    setDataSource([...dataSource])
  }

  const handleOk = () => {
    addForm.current.validateFields().then(res => {
      console.log(res)
      axios.get('123121312')
    }).catch(err => {
      console.log(err)
    })
    // 隐藏弹框
    setModalFlag(false)
    // 重置数据
    addForm.current.resetFields()
  }

  const handleCancel = () => {
    setModalFlag(false)
    addForm.current.resetFields()
  }

  // 新建
  const addUserBtn = () => {
    setBtnFlag(0)
    setUpdateFlag(false)
    let flag = false
    flag = !modalFlag
    setModalFlag(flag)
  }
  
  // 编辑
  const btnClick = (item) => {
    setTimeout(() => {
      setBtnFlag(1)
      setModalFlag(true)
      if (item.roleId === 1) {
        setUpdateFlag(true)
      } else {
        setUpdateFlag(false)
      }
      // 设置数据
      addForm.current.setFieldsValue(item)
    })
  }


  return (
    <div>
      <Button 
        type="primary"
        onClick={addUserBtn}
      >添加用户</Button>
      <Table 
        dataSource={dataSource} 
        columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={item => item.id}
      />
      <Modal 
        title={BtnFlag === 0 ? "新建用户" : "更新用户"}
        visible={modalFlag} 
        onOk={handleOk} 
        okText="确定"
        onCancel={handleCancel}
        cancelText="取消"
      >
        <UserForm 
          ref={addForm}
          regoinList={regoinList} 
          roleList={roleList}
          updateFlag={updateFlag}
        ></UserForm>
      </Modal>
    </div>
  )
}
